import ajax from "../../utils/ajax";
import laydate from "laydate-es6";
import upload from "../../utils/upload";

const form = document.forms.userInfo
const avatar = document.getElementById('avatar')

init()

async function init() {
    //初始化日历
    init_laydate();
    //默认数据填充
    reset();
    //增加表单提交
    form.onsubmit = form_onsubmit;

    form.avatar.onchange = avatar_change;
}

function init_laydate() {
    laydate.render({
        elem: "#birthday",
        max: '2023-1-5'
    })
}

async function reset() {
    const { data } = await ajax('get', '/api/getUserInfo');
    console.log(data.nickname);

    if (data.nickname) {
        form.nickname.value = data.nickname;
    }
    if (data.gender) {
        form.gender.value = data.gender.data[0] == 0 ? 'male' : 'female';
    }
    if (data.birthday) {
        form.birthday.value = data.birthday.slice(0, 10);
    }
    if (data.avatar) {
        avatar.src = 'http://127.0.0.1:3000' + data.avatar;
    }
}

function form_onsubmit(e) {
    e.preventDefault();
    const fd = new FormData(form)
    upload('/api/updateUserInfo', fd).then(result => {

    })
}

function avatar_change() {
    const that = this
    //判断文件域有没有选择文件
    if (that.files.length > 0) {
        //限定文件是图片
        if (!/^image\//.test(that.files[0].type)) {
            alert('请选择图片类型')
            that.value = null
            avatar.src = ''
            return
        }
        //限定文件尺寸
        if (that.files[0].size > 1024 * 200) {
            alert('图片大小不能超过200KB')
            that.value = null
            avatar.src = ''
            return
        }
        //文件类型和大小通过后
        avatar.src = URL.createObjectURL(that.files[0])
    } else {
        avatar.src = ''
    }
}